<?php

namespace App\Exports;

use App\Models\ModelFields;
use App\Models\Models;
use App\Models\OrderChild;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;

use Maatwebsite\Excel\Concerns\WithStyles;
//单元格格式化,单元格处理文本、数字、日期、金额等格式
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
//自动适应单元格宽
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SalaryInfoExport implements FromCollection, WithColumnFormatting, ShouldAutoSize,WithStyles
{
    /**导出**/
    private $params;

    private $title='员工工资列表';

    /**
     * @var string[] 导出标题集合
     */
    private $headingList =[
        ['员工工资详情列表','','','','','',''],
        ['','','','','','',''],
        [
        'employee_name'=>'员工名称',
        'order_num'=>'订单号',
        'product_name'=>'产品名称',
        'model_number'=>'型号',
        'specification'=>'规格',
        'submit_time'=>'完成时间',
        'price'=>'工单金额',
            ]
    ];



    public function __construct($params) {
        ob_end_clean();
        $this->params = $params;
    }




    /**
     * Notes: 处理导出数据表头
     * User: q
     * DateTime: 2021/10/13 18:10
     * @return array
     */
    public function headings(): array{

        return  [
            '员工名称',
            '订单号',
            '产品名称',

            '型号',
            '规格',
            '完成时间',
            '工单金额',
        ];
    }


    //数组转集合
    public function collection()
    {
        return new Collection($this->createData());
    }

    //业务代码
    public function createData()
    {
        $data[] = $this->headingList;
        $params = $this->params;
        $array = OrderChild::Search($params)
            ->with(['order'=>function($q){
                $q->with(['product'=>function($q){
                    return $q->select('id','product_name');
                },'customer'=>function($q){
                    return $q->select('id','customer_name','customer_address');
                },'modelNumber'=>function($q){
                    return $q->select('id','model_number');
                },'specification'=>function($q){
                    return $q->select('id','specification');
                }]);
            },
                'employee'=>function($q){
                    $q->select('user_id','employee_name','base_pay','id');
                }
            ])
            ->select('id','order_id','price','employee_user_id','submit_time')
            ->orderBy('submit_time','desc')
            ->get()->toArray();
        //p($array);
        foreach ($array as $key=>&$val){
            $product_id = $val['order']['product_id'];
            $modelid = Product::where('id',$product_id)->value('modelid');
            $tablename = Models::where('modelid',$modelid)->value('tablename');
            $model_field = ModelFields::where('modelid',$modelid)->get();

            if($model_field){
                foreach($model_field as $kk=>$vv){
                    if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                        $array[$key]['order']['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$val['order_id'])->value($vv['field']);
                    }else{
                        if(!empty($vv->option_list)){
                            $option_list = explode("\n",$vv->option_list);
                            //p($option_list);
                            $option_arr = [];
                            foreach($option_list as $keys=>$vals){
                                $option = explode("|",rtrim($vals));
                                //p($option);
                                $option_arr[$option[1]] = $option[0];
                            }
                            $field_key = DB::table($tablename)->where('order_id',$val['order_id'])->value($vv['field']);
                            //$data[$k]['models_field'][$vv->field] = $option_arr[$field_key]??'';
                            $array[$key]['order']['models_field'][$vv->field] = $field_key;
                            //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                        }else{
                            $array[$key]['order']['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$val['order_id'])->value($vv['field']);
                        }


                    }
                }
            }
            $data[] = [
                'employee_name'=>$val['employee']['employee_name']??"",
                'order_num'=>$val['order']['order_number']??"",
                'product_name'=>$val['order']['product']['product_name']??"",

                'model_number'=>$val['order']['model_number']['model_number']??"",
                'specification'=>$val['order']['specification']['specification']??"",
                'submit_time'=>$val['submit_time'],
                'price'=>$val['price']??'',
            ];
        }
        return $data;
    }




    public function columnFormats(): array
    {
        //'B' => NumberFormat::FORMAT_DATE_DDMMYYYY, //日期
        $format = NumberFormat::FORMAT_NUMBER_00;//金额保留两位小数
        return ['I' => $format];

    }


    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->title;
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 100, 'B' => 100, 'C' => 100, 'D' => 100, 'E' => 100, 'F' => 100,'G' => 100
        ];
    }




    public function styles(Worksheet $sheet)
    {
        $sheet->getDefaultRowDimension()->setRowHeight(22);//设置行高
        $sheet->mergeCells('A1:I2'); //合并单元格
        $sheet->getStyle('A1:I2')
            ->applyFromArray([
                'font' => ['bold' => true],
                'color' => ['rgb' => '0072ff']
            ]);//字体设置
        // 设置背景色
        $sheet->getStyle('A1:I2')->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setRGB('e9e9e9');

        // setWrapText自动换行，setVertical垂直对齐方式
        $sheet->getStyle("A:I")->getAlignment()->setVertical('center');
        $sheet->getStyle('A:I')->applyFromArray(['alignment' => ['horizontal' => 'center']]);//设置水平居中


    }
}
